// 调试版本的前端脚本
console.log('🐛 调试脚本已加载');

document.addEventListener('DOMContentLoaded', function() {
    console.log('🐛 DOM已加载');
    
    const form = document.getElementById('fortuneForm');
    const nameInput = document.getElementById('name');
    const birthDateInput = document.getElementById('birthDate');
    const cityInput = document.getElementById('city');
    const genderInputs = document.querySelectorAll('input[name="gender"]');
    const submitBtn = document.querySelector('.submit-btn');
    const btnText = document.querySelector('.btn-text');
    
    console.log('🐛 表单元素:', {
        form: !!form,
        nameInput: !!nameInput,
        birthDateInput: !!birthDateInput,
        cityInput: !!cityInput,
        genderInputs: genderInputs.length,
        submitBtn: !!submitBtn,
        btnText: !!btnText
    });
    
    // 表单提交处理
    form.addEventListener('submit', async function(e) {
        console.log('🐛 表单提交事件触发');
        e.preventDefault();
        
        // 收集表单数据
        const userData = {
            name: nameInput.value.trim(),
            birthDate: birthDateInput.value,
            gender: document.querySelector('input[name="gender"]:checked')?.value
        };
        
        // 添加城市信息（如果有输入）
        const city = cityInput.value.trim();
        if (city) {
            userData.city = city;
        }
        
        console.log('🐛 用户数据:', userData);
        
        // 简单验证
        if (!userData.name || !userData.birthDate || !userData.gender) {
            alert('请填写完整信息');
            return;
        }
        
        await callFortuneAPI(userData);
    });
    
    // API调用函数
    async function callFortuneAPI(userData) {
        console.log('🐛 开始API调用');
        
        try {
            // 显示加载状态
            setLoadingState(true);
            
            console.log('🐛 发送请求到:', '/api/fortune');
            console.log('🐛 请求数据:', JSON.stringify(userData, null, 2));
            
            const response = await fetch('/api/fortune', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(userData)
            });
            
            console.log('🐛 响应状态:', response.status);
            console.log('🐛 响应头:', Object.fromEntries(response.headers.entries()));
            
            if (!response.ok) {
                const errorText = await response.text();
                console.error('🐛 HTTP错误:', response.status, errorText);
                throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
            }
            
            const result = await response.json();
            console.log('🐛 API响应:', result);
            
            if (result.success) {
                console.log('🐛 API调用成功，准备跳转');
                
                // 将结果存储到localStorage
                localStorage.setItem('fortuneResult', JSON.stringify(result.data));
                console.log('🐛 数据已存储到localStorage');
                
                // 直接跳转，不使用复杂动画
                const encodedData = encodeURIComponent(JSON.stringify(result.data));
                const resultUrl = `result.html?data=${encodedData}`;
                console.log('🐛 跳转到:', resultUrl);
                
                window.location.href = resultUrl;
            } else {
                console.error('🐛 API返回错误:', result.error);
                throw new Error(result.error || '算命服务出现错误');
            }
            
        } catch (error) {
            console.error('🐛 API调用错误:', error);
            alert(`错误: ${error.message}`);
        } finally {
            setLoadingState(false);
        }
    }
    
    // 设置加载状态
    function setLoadingState(isLoading) {
        console.log('🐛 设置加载状态:', isLoading);
        
        if (isLoading) {
            submitBtn.disabled = true;
            btnText.textContent = '计算中...';
            submitBtn.style.opacity = '0.7';
        } else {
            submitBtn.disabled = false;
            btnText.textContent = '开始算命';
            submitBtn.style.opacity = '1';
        }
    }
    
    // 测试服务器连接
    async function testServerConnection() {
        console.log('🐛 测试服务器连接...');
        
        try {
            const response = await fetch('/health');
            const data = await response.json();
            console.log('🐛 服务器健康检查:', data);
            
            // 在页面上显示服务器状态
            const statusDiv = document.createElement('div');
            statusDiv.style.cssText = `
                position: fixed;
                top: 10px;
                right: 10px;
                background: #4caf50;
                color: white;
                padding: 8px 12px;
                border-radius: 4px;
                font-size: 12px;
                z-index: 1000;
            `;
            statusDiv.textContent = '服务器连接正常';
            document.body.appendChild(statusDiv);
            
        } catch (error) {
            console.error('🐛 服务器连接失败:', error);
            
            // 显示错误状态
            const statusDiv = document.createElement('div');
            statusDiv.style.cssText = `
                position: fixed;
                top: 10px;
                right: 10px;
                background: #f44336;
                color: white;
                padding: 8px 12px;
                border-radius: 4px;
                font-size: 12px;
                z-index: 1000;
            `;
            statusDiv.textContent = '服务器连接失败';
            document.body.appendChild(statusDiv);
        }
    }
    
    // 页面加载完成后测试服务器连接
    setTimeout(testServerConnection, 1000);
});

// 全局错误处理
window.addEventListener('error', function(e) {
    console.error('🐛 全局错误:', e.error);
});

window.addEventListener('unhandledrejection', function(e) {
    console.error('🐛 未处理的Promise拒绝:', e.reason);
});